<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/3/19
 * Time: 19:04
 */

namespace app\api\service;


use app\api\controller\BaseCotroller;
use app\api\model\OrderProduct;
use app\api\model\Product as ProductModel;
use app\api\model\Order as OrderModel;
use app\api\model\UserAddress;
use app\lib\enum\OrderStatusEnum;
use app\lib\exception\OrderException;
use app\lib\exception\UserException;
use think\Db;
use think\Exception;

class Order
{
    //订单的商品列表，也就是客户端传递过来的products参数
    protected $oProducts;

    //真实的商品信息，包括库存量
    protected $products;

    protected $uid;

    //生成订单，保存到数据库中并返回客户端
    public function place($uid, $oProducts){
        $this->oProducts = $oProducts;
        $this->products = $this->getProductsByOrder($oProducts);
        $this->uid = $uid;
        $status = $this->getOrderStatus();
        if (!$status['pass']){
            $status['order_id'] = -1;  //order_id 是订单的主键，-1表示订单不存在
            return $status;
        }

        //开始创建订单,存储快照信息
        $snapOrder = $this->snapOrder($status);  //生成订单快照
        $order = $this->createOrder($snapOrder);
        $order['pass'] = true;
        return $order;
    }

    //创建订单-保存订单信息到数据库
    private function createOrder($snap){
        Db::startTrans();
        try{
            $orderNo = $this->makeOrderNo();
            $order = new \app\api\model\Order();
            $order->user_id = $this->uid;
            $order->order_no = $orderNo;
            $order->total_price = $snap['orderPrice'];
            $order->total_count = $snap['totalCount'];
            $order->snap_img = $snap['snapImg'];
            $order->snap_name = $snap['snapName'];
            $order->snap_address = $snap['snapAddress'];
            $order->snap_items = json_encode($snap['pStatus']);
            $order->save();

            $orderID = $order->id;
            $creatTime = $order->create_time;

            foreach ($this->oProducts as &$p) {
                $p['order_id'] = $orderID;
            }
            $orderProduct = new OrderProduct();
            $orderProduct->saveAll($this->oProducts);
            Db::commit();

            return [
                'order_no' => $orderNo,
                'order_id' => $orderID,
                'reate_time' => $creatTime
            ];
        }catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }
    }

    //生成订单号-尽可能减少订单号的重复
    public function makeOrderNo(){
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        $orderSn =
            $yCode[intval(date('Y')) - 2018] . strtoupper(dechex(date('m'))) . date(
                'd') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf(
                '%02d', rand(0, 99));
        return $orderSn;
    }

    //订单快照，生成订单的信息
    private function snapOrder($status){
        $snap = [
            'orderPrice' => 0,  //订单总价
            'totalCount' => 0,  //订单商品的总数量
            'pStatus' => [],  //订单里每个商品的状态
            'snapAddress' => null,  //订单用户下单时的地址，
            'snapName' => '',  //订单列表页展示的商品名称
            'snapImg' => '',  //订单列表页展示的商品的图片
        ];

        $snap['orderPrice'] = $status['orderPrice'];
        $snap['totalCount'] = $status['totalCount'];
        $snap['pStatus'] = $status['pStatusArray'];
        $snap['snapAddress'] = json_encode($this->getUserAddress());
        $snap['snapName'] = $this->products[0]['name'];
        $snap['snapImg'] = $this->products[0]['main_img_url'];

        if (count($this->products) > 1){
            $snap['snapName'] .= '等';
        }
        return $snap;
    }

    //获取用户地址
    private function getUserAddress(){
        $userAddress = UserAddress::where('user_id', '=', $this->uid)
            ->find();
        if (!$userAddress){
            throw new UserException([
                'msg' => '用户收货地址不存在，下单失败',
                'errorCode' => 60001,
            ]);
        }
        return $userAddress->toArray();
    }

    //向外部提供检测库存量的方法
    public function checkOrderStock($orderID){
        $oProduct = OrderProduct::where('order_id', '=', $orderID)
            ->select();
        $this->oProducts = $oProduct;
        $this->products = $this->getProductsByOrder($oProduct);
        $status = $this->getOrderStatus();
        return $status;
    }

    //生成订单商品状态-$status
    private function getOrderStatus(){
        $status = [
            'pass' => true,  //表示订单库存量检查是否通过，默认通过
            'orderPrice' => 0,  //订单总价格
            'totalCount' => 0,  //订单所有商品总数量
            'pStatusArray' => []  //订单中所有商品的详细信息
        ];

        foreach ( $this->oProducts as $oProduct) {
            $pStatus = $this->getProductStatus($oProduct['product_id'], $oProduct['count'], $this->products);
            if (!$pStatus['haveStock']){
                $status['pass'] = false;
            }
            $status['orderPrice'] += $pStatus['totalPrice'];
            $status['totalCount'] += $pStatus['counts'];
            array_push($status['pStatusArray'], $pStatus);
        }
        return $status;
    }

    //生成单类真实商品的状态-$pStatus
    private function getProductStatus($oPID, $oCount, $products){
        $pIndex = -1;

        $pStatus = [
            'id' => null,  //真实商品的id
            'haveStock' => false,  //真实商品库存量状态，比订单多则是true
            'counts' => 0, //当前订单请求的商品数量
            'name' => '', //商品名称
            'main_img_url' => null,  //图片
            'price' => 0,  //商品单价
            'totalPrice' => 0,  //某类商品的总价
        ];

        for ($i=0; $i<count($products); $i++){
            if ($oPID == $products[$i]['id']){
                $pIndex = $i;
            }
        }
        if ($pIndex == -1){
            //客户端传递的product_id有可能根本不存在
            throw new OrderException([
                'msg' => 'id为'.$oPID.'的商品不存在，创建订单失败'
            ]);
        }else{
            $product = $products[$pIndex];
            $pStatus['id'] = $product['id'];
            $pStatus['name'] = $product['name'];
            $pStatus['main_img_url'] = $product['main_img_url'];
            $pStatus['counts'] = $oCount;
            $pStatus['price'] = $product['price'];
            $pStatus['totalPrice'] = $product['price'] * $oCount;

            if ($product['stock'] - $oCount >= 0 ){
                $pStatus['haveStock'] = true;
            }
        }
        return $pStatus;
    }

    //根据订单信息查找真实的商品信息
    private function getProductsByOrder($oProducts){
        $oPIDs = [];
        foreach ( $oProducts as $item) {
            array_push($oPIDs, $item['product_id']);
        }
        $products = ProductModel::all($oPIDs)
            ->visible(['id','name','price','stock','main_img_url'])
            ->toArray();
        return $products;
    }

    // 模板消息 已发货
    public function delivery($orderID, $jumpPage = ''){
        $order = OrderModel::where('id', '=', $orderID)
            ->find();

        if (!$order){
            throw new OrderException();
        }
        if ($order->status != OrderStatusEnum::PAID ){
            throw new OrderException([
                'msg' => '还没付款呢，想干嘛？或者你已经更新过订单了，不要再刷了。',
                'code' => 403,
                'errorCode' => 80002,
            ]);
        }
        $order->status = OrderStatusEnum::DELIVERED;
        $order->save();

        //发送消息给用户
        $message = new DeliveryMessage();
        return $message->sendDeliveryMessage($order, $jumpPage);
    }
}